package com.example.smart.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smart.mapper.AdminMapper;
import com.example.smart.mapper.MenuMapper;
import com.example.smart.mapper.UserMapper;
import com.example.smart.pojo.Admin;
import com.example.smart.pojo.User;
import com.example.smart.service.AdminService;
import com.example.smart.service.MenuService;
import com.example.smart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        /*LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getUserName, name);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user != null) {
            return new AccountUser();
            user.getUserId(), user.getUserName(), user.getPassword()*//*, getUserAuthority(user.getUserId())*//*
        }*/

        LambdaQueryWrapper<Admin> adminQueryWrapper = new LambdaQueryWrapper<>();
        adminQueryWrapper.eq(Admin::getAdminName, name);
        Admin admin = adminMapper.selectOne(adminQueryWrapper);
        if (admin != null) {
            List<String> list = menuMapper.selectPermsByAdminId(admin.getAdminId());
            AccountAdmin accountAdmin = new AccountAdmin(admin, list);
            accountAdmin.setAdmin(admin);
            //accountAdmin.setPermissions(list);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    accountAdmin.getAdmin().getAdminName(),
                    accountAdmin.getAdmin().getPassword(),
                    accountAdmin.getAuthorities()/*new ArrayList<>()*/)
            );
            return accountAdmin;
        }
        //return new AccountAdmin();
        throw new RuntimeException("User not found with username: " + name);
    }
}
